const fs = require('fs')

function FileUtil () {

    this.imageToBase64simple = function(imagePath, callback) {
        fs.readFile(imagePath, (err, data) => {
            if (err) {
                console.error(err);
                return;
            }
            // Convert binary data to base64 encoded string
            const base64Image = data.toString('base64')
            //console.log('base64Image',base64Image)
            callback(base64Image);
        });
    }

    this.imageToBase64 = function(imagePath, callback) {
        fs.readFile(imagePath, (err, data) => {
            if (err) {
                console.error(err);
                return;
            }
            // Convert binary data to base64 encoded string
            const base64Image = 'data:image/png;base64,' + data.toString('base64')
            //console.log('base64Image',base64Image)
            callback(base64Image);
        });
    }

    this.base64ToFile = function(base64Data, filePath) {
        // 移除Base64字符串的数据头部（如'data:image/png;base64,'）
        var strs = base64Data.split(',')
        const data = strs.length>1?strs[1]:strs[0];

        // 使用Buffer转换Base64字符串到二进制数据
        const buffer = Buffer.from(data, 'base64');

        // 将Buffer数据写入文件
        fs.writeFileSync(filePath, buffer);

        console.log('文件已保存至: ', filePath);
    }
}

export default new FileUtil()
